let token = getToken();
let user = JSON.parse(window.localStorage.getItem("userInfo"));
let url;
let currentNodeName = null;
var treeData = []
var isShow27 = false
let activeCard = ''
let promiseList = [];
var res = playGet(`/v1/api/team/tu/${user.id}`);
if (res.code == 200) {
  const isC1Fun = (currentNode) => {
    if (isShow27) {
      $(".other-next-container").show()
    } else {
      $(".other-next-container").hide()
    }
  }
  const getTeamTu = (res) => {
    const {
      data
    } = res;
    if (data && data.length > 1) {
      isShow27 = false
    } else {
      isShow27 = true
    }
    isC1Fun()
    for (let i = 1; i < 4; i++) {
      const promiseFunc = new Promise((resolve) => {
        resolve(
          $.ajax({
            url: `${server}/v1/api/setting/tj/queue/zhu/${data[0]}/${i}`,
            // url: `http://47.111.243.54:504/v1/api/setting/tj/queue/zhu/1/${i}`, // 有数据
          })
        );
      });
      promiseList.push(promiseFunc);
    }
  }
  getTeamTu(res)
  const showCurrentUserAtTreeChart = (pnum) => {
    const otherNode = $(".other");
    for (let i = 0; i < otherNode.length; i++) {
      if (String(pnum) === otherNode.eq(i).text()) {
        otherNode.eq(i).addClass("active");
      }
    }
  };

  const setLastShowNode = (list) => {
    console.log('list', list)
    const otherNode = $(".other-next");
    // 先清空所有的内容
    for (let i = 0; i < otherNode.length; i++) {
      otherNode.eq(i).find('.text').html("")
      otherNode.eq(i).attr('userName', '')
      otherNode.eq(i).attr('mobile', '')
      otherNode.eq(i).removeClass('other-next-bg')
    }
    for (let i = 0; i < otherNode.length; i++) {
      const nodeVal = Number(otherNode.eq(i).find('.cache-value').html());
      list.map(item => {
        if(item.pnum == nodeVal) {
          otherNode.eq(i).find('.text').html(nodeVal)
          otherNode.eq(i).attr('userName', item.userName)
          otherNode.eq(i).attr('mobile', item.mobile)
          otherNode.eq(i).addClass('other-next-bg')
        }
      })
    }
  };
  $(".other-next").on('click', (e) => {
    if($(e.target).html()) {
      $('#showTeamDetail').show()
      $('#detailUserName').html($(e.target).attr('userName'))
      $('#detailMobile').html($(e.target).attr('mobile'))
    }
  })
  $(document).on('click', (e) => {
    if($(e.target).attr('userName')) {
      $('#showTeamDetail').show()
      $('#detailUserName').html($(e.target).attr('userName'))
      $('#detailMobile').html($(e.target).attr('mobile'))
    } else {
      $('#showTeamDetail').hide()
    }
  })
  const toRenderTeamList = (list) => {
    console.log('toRenderTeamList',list)
    const allPnum = [];
    const teamListContainer = $("#dataList");
    let allTeamListNode = list
    let allTeamData = []
      list.map((i) => {
        const { code, data } = i;
        if (data.length > 0) {
          data.map((j, jIndex) => {
              allTeamData.push(j)
              const { id, pnum, name, mobile, userName } = j;
              allPnum.push(pnum);
            })
        }
      })
    let maxPnum = allPnum.length > 0 ? allPnum.reduce((a, b) => (a > b ? a : b)) : 0
    setLastShowNode(allTeamData, maxPnum)
    teamListContainer.append(allTeamListNode);
  };
  var allCardData = {}
  var showAllTree = []
  var currentNode = []
  var fatherIds = []
  var dir = 'next'
  const getLeverData = (data, id) => {
    let userId = id || JSON.parse(localStorage.getItem("userInfo")).id
    if (!Array.isArray(data) && data && data.id === userId) {
      currentNode = [data]
      showAllTree = [data]
      return data
    }
    if (data === null) return []
    if (Array.isArray(data)) {
      for (let item of data) {
        if (item.id === userId) {
          if (id) {currentNode = data} else {showAllTree = data}
          
          return data
        } else {
          // fatherId = item.id
          getLeverData(item.children, id)
        }
      }
    } else {
      getLeverData(data.children, id)
    }
    
    
  }
  $('#treeDataList').on('click', function(e){
    if (!$(e.target).hasClass('to-right')) {
      //  选中卡片
      if ($(e.target).hasClass('li-click')){
        activeCard = $(e.target).attr('userId')
        judgeCardActive()
        res = playGet(`/v1/api/team/tu/${activeCard}`);
        promiseList = []
        res.code === 200 && getTeamTu(res)
        Promise.allSettled(promiseList)
          .then((res) => {
            const teamListData = [];
            res.forEach((i) => {
              const { status, value } = i;
              if (status !== "fulfilled") return console.log("数据获取失败");
              teamListData.push(value);
            });
            return teamListData;
          })
          .then(toRenderTeamList)
      } else {
        return
      }
      return
    }
    const userId = $(e.target).attr('userId')
    new Promise((resolve) =>
      resolve(
        $.ajax({
          url: `${server}/v1/api/team/node/son/${userId}`,
        })
      )
    ).then(res => {
          let right = '>'
          let left = '<'
          if (res.data === null) return
          const list = res.data.map(item => {
            const teamListTemplate = getTemplate(item, item.pnum<2 ?right: '')
              return teamListTemplate
          }).join("")
          $('#treeDataList').addClass('has-left')
          fatherIds.push(userId)
          dir = 'next'
          const toLeft = `<li class="to-left" id="toLeft" fatherId="${userId}">${left}</li>`
        $("#treeDataList").html(toLeft+list)
        judgeCardActive()
    })
    
  })
  $('#treeDataList').on('click', function(e){
    if (!$(e.target).hasClass('to-left')) return
    let data = allCardData
    getLeverData(data, $(e.target).attr('fatherId'))
    data = currentNode
    const list = data.map(item => {
      const teamListTemplate = getTemplate(item, '>')
        return teamListTemplate
    }).join("")
    $('#treeDataList').addClass('has-left')
    const left = '<'
    if (dir === 'next') {
      fatherIds.pop()
      dir = 'prv'
    }
    let fatherId = fatherIds[fatherIds.length - 1]
    const toLeft = fatherIds.length > 0 ?`<li class="to-left" id="toLeft" fatherId="${fatherId}">${left}</li>`: ''
    fatherIds.length > 0 ? $('#treeDataList').addClass('has-left') : $('#treeDataList').removeClass('has-left')
    fatherIds.pop()
    $("#treeDataList").html(toLeft+list)
    judgeCardActive()
  })
  const getTemplate = (item, right) => {
    let html = `
    <li class="card-right li-click" userId="${item.id}" queueId="${item.queueId}">
      <img src="phoneContent/img/headImg.png" class="li-click"  userId="${item.id}" queueId="${item.queueId}"/>
      <div class="fr li-click" userId="${item.id}" queueId="${item.queueId}">
        <p class="t_name li-click" userId="${item.id}" queueId="${item.queueId}">账号:${item.name}</p>
        <p class="t_name li-click" userId="${item.id}" queueId="${item.queueId}">手机号:${item.mobile}</p>
      </div>
    `
    let rightHtml = `<div class="to-right" userId="${item.id}">${right}</div>`
    let temp = right ? html + rightHtml + `</li>` : html + '</li>'
    return temp;
  }

  const toRenderTreeNode = (resData) => {
    const treeContainer = $("#tree_chart_container");
    let { code, data } = resData;
    allCardData = data
    if (!data) {
      treeContainer.show();
      treeContainer
        .children(".other-next-container")
        .eq(0)
        .addClass("not-top-line");
      return;
    }
    if (code === 200 && data) {
      treeContainer.show();
      new Promise((resolve) =>
      resolve(
        $.ajax({
          url: `${server}/v1/api/team/node/brother/${user.id}`,
        })
      )
    ).then(res => {
      // 树
      getTreeData(Array.isArray(res.data) ? res.data : [res.data])
    })
    }
  };
  const getTreeData = (data) => {
    getLeverData(allCardData)
    let right = '>'
    const list = data.map(item => {
      const teamListTemplate = getTemplate(item, item.pnum<2 ?right: '')
        return teamListTemplate
    }).join("")
    $("#treeDataList").html(list)
    activeCard = user.id
    judgeCardActive()
  }
  const judgeCardActive = () => {
    let listNode = $("#treeDataList").find('.card-right')
    for (let i = 0; i < listNode.length; i++) {
      let userId = listNode.eq(i).attr('userId')
      if (userId === activeCard) {
        listNode.eq(i).addClass('card-list-active')
      } else {
        listNode.eq(i).removeClass('card-list-active')
      }
    }
  }
  function getNodeData() {
    new Promise((resolve) =>
      resolve(
        $.ajax({
          // 获取完整树
          url: `${server}/v1/api/setting/tj/queue/1`,
        })
      )
    )
      .then(toRenderTreeNode)
      .then(() => {
        Promise.allSettled(promiseList)
          .then((res) => {
            const teamListData = [];
            res.forEach((i) => {
              const { status, value } = i;
              if (status !== "fulfilled") return console.log("数据获取失败");
              teamListData.push(value);
            });
            return teamListData;
          })
          .then(toRenderTeamList)
          .catch((err) => console.log(err));
      });
  }

  getNodeData();
}
  else {
    mui.alert(res.msg);
  }
